import { Dimensions } from "@sapi-game/constants";
import { GameComponent } from "@sapi-game/gameComponent";
import { CubeRegion } from "@sapi-game/gameRegion/gameRegion";
import { regionHelper } from "@sapi-game/main";
import { Vector3Utils } from "@sapi-game/utils";
import { EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { DirtShopLoadState } from "../states/loadState";

export class DirtShopMapLoader extends GameComponent<DirtShopLoadState> {
    protected override onAttach(): void {
        const region = this.context.map.region;
        //添加常加载
        Dimensions.Overworld.runCommand(
            `tickingarea add ${Vector3Utils.toString(
                region.pos1,
                " "
            )} ${Vector3Utils.toString(region.pos2, " ")}`
        );
        //步骤
        this.runner.run(async (r) => {
            await r.wait(10);
            this.context.groupSet.title("地图重置中.", "清空区域");
            await this.fillAir(); //清空区域
            await r.wait(2);
            this.killEntity(); //杀
            await r.wait(5);
            this.context.groupSet.title("地图重置中..", "生成草地");
            await this.genBase(); //生成草坪
            await r.wait(5);
            this.context.groupSet.title("地图重置中...", "生成结构");
            r.do(() => this.genStructures());
            await r.wait(20);
            this.context.groupSet.title("地图重置完成");
            await r.wait(20);
            //进入下一阶段
            this.state.next();
        });
    }

    protected override onDetach(): void {
        const region = this.context.map.region;
        //删除常加载
        Dimensions.Overworld.runCommand(
            `tickingarea remove ${Vector3Utils.toString(region.pos1, " ")}`
        );
    }

    fillAir() {
        const gen = regionHelper.fillGenerator(this.context.map.region, "air");
        const ans = this.runner.runJob(gen);
        return ans.promise;
    }

    killEntity() {
        const entites = this.context.map.region.getEntitesInRegion({
            excludeTypes: [EntityTypeIds.Player],
        });
        entites.forEach((e) => e.remove());
    }

    async genBase() {
        const layers = ["bedrock", "dirt", "dirt", "grass"];
        const region = this.context.map.region;
        const min = region.getMin();
        const max = region.getMax();
        let y = min.y;
        for (let layer of layers) {
            const layerRegion = new CubeRegion(
                region.dimensionId,
                { x: min.x, y: y, z: min.z },
                { x: max.x, y: y, z: max.z }
            );
            const gen = regionHelper.fillGenerator(layerRegion, layer);
            const { promise } = this.runner.runJob(gen);
            await promise;
            y++;
        }
    }

    genStructures() {
        for (const structure of this.context.map.structures) {
            structure.place();
        }
    }
}
